package ltd.simulatoruidemo.util;

import android.util.Log;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.IOException;

import ltd.simulatoruidemo.constant.ConfigConstant;

/**
 * 文件操作工具类
 *
 * Created by chinalin on 2017/3/27.
 */
public final class FileUtil {
    private static final String TAG = "FileUtil" ;
//    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class) ;

    /**
     * 获取真实文件名(自动去掉文件路径)
     */
    public static String getRealFileName(String fileName){
        return FilenameUtils.getName(fileName) ;
    }

    /**
     * 创建文件(文件路径不存在，创建路径+文件）
     */
    public static File createFile(String filePath){
        File file ;
        try {
            file = new File(filePath) ;
            File parentDir = file.getParentFile() ;
            if (!parentDir.exists()){
                FileUtils.forceMkdir(parentDir);
            }
        }catch (Exception e){
            Log.e(TAG,"create file failure " + e.toString()) ;
//            LOGGER.error("create file failure ", e);
            throw new RuntimeException(e) ;
        }
        return file;
    }

    /**
     * 将String写入文件，没有文件则创建，有则覆盖
     * @param data
     * @param fileName
     * @throws IOException
     */
    public static void writeStringToFile(String data, String fileName) throws IOException {
        File file = new File(fileName) ;
        FileUtils.touch( file );
        FileUtils.writeStringToFile(file,data, ConfigConstant.LTDCHARSET);
    }

    /**
     *  从文件读出String，文件不存在则返回""
     * @param fileName
     * @throws IOException
     */
    public static String readStringFromFile(String fileName) throws IOException {
        File file = new File(fileName) ;
        String result = "" ;
        if (file.exists()){
            result = FileUtils.readFileToString(file,ConfigConstant.LTDCHARSET) ;
        }
        return result;
    }
}
